'''
Created on 22.01.2013

@author: doleynik
'''
import cgi
import time
import webapp2

from webapp2_extras.i18n import gettext as _


from google.appengine.api import users
from apnetmodels.basicmodels import syndic, syndicForUser, immeuble, account, VAT
from apnetmodels.apnetusers import APNETUser
from common import functions
from wtforms.ext.appengine.db import model_form

from BaseHandler import BaseHandler

class Registration(BaseHandler):
    def get(self, command=None):
        if command == 'user' or not command:
            self.op_add_user()
        if command == 'syndic':
            self.op_add_syndic()
        if command == 'tenement':
            self.op_add_tenement()
            
    def post(self, command=None):
        if command == 'user' or not command:
            self.op_add_user()
        if command == 'syndic':
            self.op_add_syndic()
        if command == 'tenement':
            self.op_add_tenement()


    def op_add_user(self):
        
        # check and define initial parameters #
        test_acc = account.all().get()
        if not test_acc:
            self.init_common_data()
        
        # new user registration #
        
        au = functions.GetAPNETUser()
        if au:
            return self.redirect(webapp2.uri_for('registration', command="syndic"))

        
        user = users.get_current_user()
        APNETUserForm = model_form(APNETUser, exclude=['state',
                                                       'last_active_immeuble_id',
                                                       'is_syndic_creator',
                                                       'is_syndic_admin',
                                                       'is_immeuble_admin',
                                                       'is_lot_owner'])
        
        if self.request.method == 'GET':
            form = APNETUserForm()
            form['primary_email'].data = user.email()

        if self.request.method == 'POST':
            form = APNETUserForm(self.request.POST)
            if form.validate():
                au = APNETUser(first_name = form['first_name'].data.strip(),
                               last_name = form['last_name'].data.strip(), 
                               primary_phone=form['primary_phone'].data,
                               primary_email=form['primary_email'].data.strip(),
                               lang = form['lang'].data,
                               is_syndic_creator = True,
                               is_syndic_admin = True,
                               is_immeuble_admin = True,  
                               key_name = user.email())
                au.put()
                while not au.is_saved():
                    time.sleep(2)
                return self.redirect(webapp2.uri_for('registration', command="syndic"))
                
                
            
        h = _("New applicant registration")
        title = _("Real estate management application")
        header = _("ATENET. Real estate management application")
        template_values = {
                'title': title,
                'header': header,
                'content_header': h,
                'form': form
            }
        
        template = self.jinja2.get_template('templates/reg_page.html')
        self.response.out.write(template.render(template_values))

    def op_add_syndic(self):
        
        au = functions.GetAPNETUser()
        if not au:
            return self.redirect(webapp2.uri_for('registration', command="user"))
            
        
        SyndicForm = model_form(syndic, only=['name','adress'])
       
        
        if self.request.method == 'GET':
            form = SyndicForm()
        if self.request.method == 'POST':
            form = SyndicForm(self.request.POST)
            if form.validate():
                my_syndic = syndic( name = form['name'].data.strip(),
                                    adress = form['adress'].data.strip(),
                                    creator = au, 
                                    lastchange_by = au)
                my_syndic.put()
                while not my_syndic.is_saved():
                    time.sleep(2)
                my_syndic.set_predefine_worktypes()    
                my_syndic.set_predefine_lottypes()
                syndic_user = syndicForUser(syndic = my_syndic, user=au)
                syndic_user.put()
                while not syndic_user.is_saved():
                    time.sleep(2)
                return self.redirect(webapp2.uri_for('registration', command="tenement"))
                
        h = _("Initial syndic registration")
        title = _("Real estate management application")
        header = _("ATENET. Real estate management application")
        template_values = {
                'title': title,
                'header': header,
                'content_header': h,
                'form': form,
            }
        
        template = self.jinja2.get_template('templates/reg_page.html')
        self.response.out.write(template.render(template_values))

    def op_add_tenement(self):

        au = functions.GetAPNETUser()
        if not au:
            return self.redirect(webapp2.uri_for('registration', command="user"))
        
        syn = None
        for s in  au.user_syndics.run():
            syn = s.syndic

        if not syn:
            return self.redirect(webapp2.uri_for('registration', command="syndic"))
        
        immeubleForm = model_form(immeuble, only=['name',
                                                  'adress',
                                                  'additional_adress',
                                                  'pobox',    
                                                  'neighborhood',    
                                                  'city',   
                                                  'state',    
                                                  'zip',    
                                                  'building_permit_date',
                                                  'building_permit_number',
                                                  'bulding_completion_date',
                                                  'building_cert_date',
                                                  'currency',
                                                  'note',
                                                  'water_cnt',
                                                  'hotwater_cnt',
                                                  'heating_cnt'])
        
        if self.request.method == 'GET':
            form = immeubleForm()
            
        if self.request.method == 'POST':
            form = immeubleForm(self.request.POST)
            if form.validate():
                imm = immeuble(name=form['name'].data, syndic=syn)
                form.populate_obj(imm)
                imm.lastchange_by = au
                imm.put()
                while not imm.is_saved():
                    time.sleep(2)
                au.last_active_immeuble_id = imm.key().id()
                au.put()
                imm.set_predefine_subaccounts(au)
                imm.set_predefine_chargeskeys(au)
                imm.set_predefine_expenditures(au)
                return self.redirect(webapp2.uri_for('immeuble', imm_id=imm.key().id(),  command="detail"))

        h = _("Tenement registration")
        title = _("Real estate management application")
        header = _("ATENET. Real estate management application")
        template_values = {
                'title': title,
                'header': header,
                'content_header': h,
                'form': form,
                'app_user': au
            }
        
        template = self.jinja2.get_template('templates/reg_page.html')
        self.response.out.write(template.render(template_values))

    
    def init_common_data(self):
        new_accounts = [{'code':'10' ,'title':'PROVISIONS ET AVANCES'},
                        {'code':'102','title':'PROVISIONS POUR TRAVAUX DECIDES'},
                        {'code':'103','title':'AVANCES'},
                        {'code':'12','title':'SOLDE EN ATTENTE SUR TRVX ET OPERATIONS EXCEPT.'},
                        {'code':'13','title':'SUBVENTIONS'},
                        {'code':'40','title':'FOURNISSEURS'},
                        {'code':'42','title':'PERSONNEL'},
                        {'code':'43','title':'SECURITE SOCIALE ET AUTRES ORGANISMES SOCIAUX'},
                        {'code':'44','title':'ETAT ET COLLECTIVITES TERRITORIALES'},
                        {'code':'45','title':'COLLECTVITE DES COPROPRIETAIRES'},
                        {'code':'46','title':'DEBITEURS ET CREDITEURS DIVERS'},
                        {'code':'47','title':"COMPTE D'ATTENTE"},
                        {'code':'48','title':'COMPTE DE REGULARISATION'},
                        {'code':'49','title':'DEPRECIATION DES COMPTES DE TIERS'},
                        {'code':'50','title':'FONDS PLACES'},
                        {'code':'51','title':'BANQUES, OU FONDS DISPONIBLES EN BANQUE'},
                        {'code':'53','title':'CAISSES'},
                        {'code':'60','title':'ACHATS DE MATERIELS ET FOURNITURES'},
                        {'code':'61','title':'SERVICES EXTERIEURS'},
                        {'code':'62','title':"FRAIS D'ADMINISTRATION"},
                        {'code':'63','title':'IMPOTS-TAXES ET VERSEMENT ASSIMILES'},
                        {'code':'64','title':'FRAIS DE PERSONEL'},
                        {'code':'66','title':'CHARGES FINANCIERES DES EMPRUNTS, AGIOS OU AUTRES'},
                        {'code':'67','title':'CHARGES TRAVAUX ET OPERATIONS EXCEPTIONELLES'},
                        {'code':'671','title':'TRAVAUX DECIDES PAR ASSEMBLEE GENERALE'},
                        {'code':'68','title':'DOTATIONS AUX DEPRECIATIONS SUR CREANCES DOUTEUSES'},
                        {'code':'70','title':'APPEL DE FONDS'},
                        {'code':'701','title':'PROVISIONS SUR OPERATIONS COURANTES'},
                        {'code':'702','title':"PROVISIONS SUR TRAVAUX DE L'ARTICLE 14-2"},
                        {'code':'703','title':'AVANCES'},
                        {'code':'71','title':'AUTRE PRODUITS'},
                        {'code':'78','title':'REPRISES DE DEPRECIATIONS SUR CREANCES DOUTEUSES'}]

        VATs = [{"name": "No TVA", "value": 0.0, "key":"no_TVA"},
                {"name": "Taux de TVA normal",   "value": 19.6, "key":"TVA_normal"},
                {"name": "Taux de TVA reduit 1", "value": 7.0, "key":"TVA_reduit_1"},
                {"name": "Taux de TVA reduit 2", "value": 2.1, "key":"TVA_reduit_2"}]

        for a in new_accounts:
            r = account(code=a['code'], name=a['title'], key_name = a['code'])
            r.put()
            while not r.is_saved():
                time.sleep(2)
            
        for v in VATs:
            r = VAT(name=v['name'], value=v['value'], key_name = v['key'])
            r.put()
            while not r.is_saved():
                time.sleep(2)
        